package com.xxl.job.admin.service.impl;

import java.security.MessageDigest;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import com.xxl.job.admin.core.util.PropertiesUtil;
import com.xxl.job.admin.core.util.StringUtil;
import com.xxl.job.admin.service.XinAuthService;
import com.xxl.job.core.log.XxlJobLogger;

@Service
public class XinAuthServiceImpl implements XinAuthService {
	
	
	@Override
	public boolean validateHeaderAuth(HttpServletRequest request) {
		
		String auth = request.getHeader("Auth");
		String jsonString = request.getHeader("Data");
		String configName = "xin-schedule.properties";
		Properties prop = PropertiesUtil.loadProperties(configName) ;
		String key = prop.getProperty("xin.schedule.auth.key");
    	TreeMap<String, String> reqParams = (TreeMap) new JSONObject(jsonString).toMap();     	
    	String hash = creatHash(reqParams, key);
    	logMap.put("hash", hash);
    	if(hash.equalsIgnoreCase(auth)) {
    		return true;
    	} else {
    		return false;
    	}
	}
	
	@Override
	public boolean validateUrlAuth(HttpServletRequest request) {
		
		String auth = request.getHeader("Auth");
		String jsonString = request.getHeader("Data");
		String configName = "xin-schedule.properties";
		Properties prop = PropertiesUtil.loadProperties(configName) ;
		String key = prop.getProperty("xin.schedule.auth.key");
    	Map<String, String[]>reqParams = request.getParameterMap();
    	StringUtil util = new StringUtil();
    	TreeMap<String, String> uniqueParams = new TreeMap<String, String>();
    	for (String in : reqParams.keySet()) {
    		String[] value = reqParams.get(in);
    		System.out.println(in);
    		uniqueParams.put(in, StringUtil.join(value, ","));
    	}
    	String hash = creatHash(uniqueParams, key);
    	logMap.put("hash", hash);
    	if(hash.equalsIgnoreCase(auth)) {
    		return true;
    	} else {
    		return false;
    	}
	}
	
	/**
	 * 创建hash 字符串
	 * 
	 * @param paramMap
	 * @param key
	 * @return
	 */
	public static String creatHash(TreeMap<String, String>paramMap, String key)
	{
		String paramString,hash = "";
		int i = 0;
		String[] param = new String[paramMap.keySet().size()];
		for(String k : paramMap.keySet())
		{
			param[i] = k + "=" + paramMap.get(k);
			i++;
		}
		paramString = StringUtil.join(param, "&");
    	try {
    		MessageDigest md = MessageDigest.getInstance("MD5");
    		paramString += key;
    		logMap.put("paramString", paramString);
    		hash = StringUtil.Md5Encode(paramString);
    	} catch (Exception e) {
    		
    	}
    	return hash;
	}
	
	 
	
	
}
